import { defineComponent, reactive, onMounted, watch, ref } from 'vue';
import * as echarts from 'echarts';

// 定义API响应类型
interface HospitalData {
  hospitalCode: string;
  number: string;
}

// 定义 Drawsd 组件
const Drawsd = defineComponent({
  props: {
    cdata: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    const chartRef = ref();
    let options = {};
    
    // 初始数据
    let dataFY = [['15.5', 36, 100, 90, 0.46, 18, 6, '0']];
    let dataPJ = [['29', 36, 45, 125, 0.82, 34, 23, '0']];
    let dataPD = [['22', 20, 50, 100, 0.6, 20, 10, '0']];

    // 根据医院代码更新数据
    const updateHospitalData = (hospitalData: HospitalData[]) => {
      hospitalData.forEach(item => {
        // 根据医院代码更新对应数据数组的最后一个元素
        switch(item.hospitalCode) {
          case "01":
            dataFY = dataFY.map(row => [...row.slice(0, 7), item.number]);
            break;
          case "02":
            dataPJ = dataPJ.map(row => [...row.slice(0, 7), item.number]);
              break;
          case "04":
            dataPD = dataPD.map(row => [...row.slice(0, 7), item.number]);
            break;
          // 可以添加更多医院代码的处理
        }
      });
    };

    // 监听cdata变化，更新图表
    watch(
      () => props.cdata,
      (val: any) => {
        // 如果有医院数据，更新数据数组
        if (val.hospitalData && val.hospitalData.length > 0) {
          updateHospitalData(val.hospitalData);
        }

        options = {
          color: ['#6888FC', '#E36F0F', '#FF5733'],
          legend: {
            top: 10,
            data: ['汾阳', '浦江', '浦东'],
            textStyle: {
              fontSize: 16
            }
          },
          grid: {
            left: '10%',
            right: 150,
            top: '18%',
            bottom: '10%'
          },
          tooltip: {
            backgroundColor: 'rgba(255,255,255,0.7)',
            formatter: function (param: any) {
              const value = param.value;
              return '<div style="border-bottom: 1px solid rgba(255,255,255,.3); font-size: 18px;padding-bottom: 7px;margin-bottom: 7px">'
                + param.seriesName + '：'
                + value[7] + '个'
                + '</div>';
            }
          },
          xAxis: {
            type: 'value',
            name: '日期',
            nameGap: 16,
            nameTextStyle: {
              fontSize: 16
            },
            max: 31,
            splitLine: {
              show: false
            },
            show: false
          },
          yAxis: {
            max: 70,
            type: 'value',
            name: 'AQI指数',
            nameLocation: 'end',
            nameGap: 20,
            nameTextStyle: {
              fontSize: 16
            },
            splitLine: {
              show: false
            },
            show: false
          },
          series: [
            {
              name: '汾阳',
              type: 'scatter',
              itemStyle: {
                opacity: 0.8,
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: 'rgba(0,0,0,0.3)'
              },
              data: dataFY,
              symbolSize: 80
            },
            {
              name: '浦东',
              type: 'scatter',
              itemStyle: {
                opacity: 0.8,
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: 'rgba(0,0,0,0.3)'
              },
              data: dataPD,
              symbolSize: 80
            },
            {
              name: '浦江',
              type: 'scatter',
              itemStyle: {
                opacity: 0.8,
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: 'rgba(0,0,0,0.3)'
              },
              data: dataPJ,
              symbolSize: 80
            }
          ]
        };

        if (chartRef.value) {
          chartRef.value.initChart(options);
        }
      },
      {
        immediate: true,
        deep: true
      }
    );

    return () => {
      const height = "250px";
      const width = "400px";
      return (
        <div>
          <echart ref={chartRef} height={height} width={width} />
        </div>
      );
    };
  }
});

// 主组件
export default defineComponent({
  components: {
    Drawsd
  },
  setup() {
    const cdata = reactive({
      schema: [
        { name: 'date', index: 0, text: '信息内容' },
        { name: 'AQIindex', index: 1, text: '信息内容' },
        { name: 'PM25', index: 2, text: '信息内容' },
        { name: 'PM10', index: 3, text: '信息内容' },
        { name: 'CO', index: 4, text: '信息内容' },
        { name: 'NO2', index: 5, text: '信息内容' },
        { name: 'SO2', index: 6, text: '信息内容' }
      ],
      barData: [4600, 5000, 5500, 6500, 7500, 8500],
      rateData: [],
      hospitalData: [] as HospitalData[] // 新增：存储医院数据
    });

    // 从API获取医院统计数据
    const fetchHospitalData = async () => {
      try {
        const response = await fetch(
           window.globalConfig.baseApi +'/api/Nurse/GetAllStatisticsDataBRGLJson?IIIDataType=在院病人概览&flag=2'
        );
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data: HospitalData[] = await response.json();
        cdata.hospitalData = data;
        console.log('获取医院数据成功:', data);
      } catch (error) {
        console.error('获取医院数据失败:', error);
      }
    };

    const setData = () => {
      for (let i = 0; i < cdata.barData.length - 1; i++) {
        const rate = cdata.barData[i];
        cdata.rateData.push(rate.toFixed(2));
      }
    };

    onMounted(() => {
      setData();
      fetchHospitalData(); // 组件挂载时获取医院数据
    });

    return () => {
      return (
        <div>
          <Drawsd cdata={cdata} />
        </div>
      );
    };
  }
});
